// Internal action code for project skygarden

package math;

import java.util.HashSet;
import java.util.Set;
import env.GardenModel;
import jason.environment.grid.Location;
import jason.asSemantics.*;
import jason.asSyntax.*;

@SuppressWarnings("serial")
public class closest_pos extends DefaultInternalAction {
	
	GardenModel model = GardenModel.get();
	Set<Location> set  = model.ValidLocation();
	Set<Location> store = new HashSet<Location>(set.size());
	
    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
    	
        int nbOfVeg = (int)((NumberTerm)args[0]).solve();
        if(nbOfVeg==0) {
        	store = new HashSet<Location>();
        	return true;
        }
        int fromx = (int)((NumberTerm)args[1]).solve();
        int fromy = (int)((NumberTerm)args[2]).solve();
       
        Location f = new Location(fromx,fromy);
        Location result  = null;
        boolean found = false;
        
        for (Location location : set) {
			if(check(f,location) && !store.contains(location)) {
				result  = location;
				store.add(location);
				found = true;
				break;
			}
		}
        
        if(found) {
            un.unifies(args[3], new NumberTermImpl(result.x));
            un.unifies(args[4], new NumberTermImpl(result.y));
            return true;
        } 
        return false;
    }
    //((6,13),(7,12))
    public boolean check(Location from, Location to) {
    	if(from.distance(to)==1) {
    		return true;
    	}
    	return false;
    }
}
